<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<input type="file" class="myimg" />
		<button>点击我发送ajaxpost数据</button>
		
		<script type="text/javascript">
			
				var btn = document.querySelector("button");
				btn.onclick = function(){
						ajax({
							url:"./post.php",
							method:"POST",
							data:{
								username:"张三",
								age:20,
								height:"178cm"
							},
							async:true,
							dataType:"json",
							success(res){
								console.log(res);
							}
						});
					
				}
				
					
				
				// 发送post请求发送文件
				let inputEle = document.querySelector(".myimg");
				
				inputEle.onchange = function(){
					 var file = this.files[0];
					 // console.log(file);
					 var form = new FormData();
					 form.append("img",file);
					 ajax({
						 url:"file.php",
						 data:form,
						 method:"post",
						 dataType:"json",
						 ContentType:false, //需要文件上传
						 success(res){
							 console.log(res);
						 }
					 })
					
				}
				
				
				
				function ajax(opts){
					const o2s = (obj)=>{
						let keys = Object.keys(obj);
						let values = Object.values(obj);
						return keys.map((key,k)=>`${key}=${values[k]}`).join("&");
					}
					
					let {url="",method="GET",data={},async=true,success=function(){},dataType="text",ContentType=true} = opts;
						// console.log(url,method,data,async);
					let xhr = new XMLHttpRequest();
					// console.log(data);
					// {username:zhangsan,age:20} -----> ?username=zhangsan&age=20
					if(method.toLowerCase()=="get"){
						url = url + "?" + o2s(data);
					}
					
					xhr.open(method,url,async);
					
					if(method.toLowerCase()=="post" && ContentType){
						xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
					}
					
					
					xhr.onload = function(){
						if(dataType=="text"){
							success(xhr.responseText)
						}else{
							success(JSON.parse(xhr.responseText));
						}
					}
					if(method.toLowerCase()=="post"){
						if(ContentType){
							var str = o2s(data);  // name=zhang&age=20
							xhr.send(str);
						}else{
							xhr.send(data);
						}
							
					}else{
						xhr.send();
					}
					
				}
				// 把对象转成  字符串{username:zhangsan,age:20} -----> ?username=zhangsan&age=20
				// function o2s(obj){
				// 	let keys = Object.keys(obj);
				// 	let values = Object.values(obj);
					
				// 	let arr = keys.map((key,k)=>{
				// 		return `${key}=${values[k]}`;
				// 	})
				// 	// console.log(arr);
				// 	return  arr.join("&")
				// }
				
				// const o2s = (obj)=>{
				// 	let keys = Object.keys(obj);
				// 	let values = Object.values(obj);
				// 	return keys.map((key,k)=>`${key}=${values[k]}`).join("&");
				// }
				
				
				// console.log( o2s({name:"张三",age:20,height:"178cm"}));
			
			
			
		</script>
	</body>
</html>
